package com.service.calculate;

import java.util.concurrent.PriorityBlockingQueue;

import com.service.bean.Road_GpsSignal;
import com.service.bean.Road_GpsSignal_Dumper;
import com.service.bean.Road_GpsSignal_Paver;
import com.service.bean.Road_GpsSignal_Roller;
import com.service.bean.Road_Vehicle;
import com.service.bean.alarm.RoadAlarmInfo;
import com.service.bean.alarm.RoadAlarmRule;
import com.service.bean.signal.GpsSignalWork;
import com.service.cache.CacheManager;
import com.service.other.Logger;

public class Road_ScalarCal implements Runnable {
	
	@Override
	public void run() {
		try {
			PriorityBlockingQueue<Road_GpsSignal> signals = CacheManager.instance().getSignalQueue_Road(Thread.currentThread().getName());
			Road_GpsSignal signal = null;
			while ((signal = signals.poll()) != null) {
				Road_Vehicle vehicle = CacheManager.instance().getVehicle_Road(signal.gpsNo);
				new Road_SignalCreator(signal,vehicle).createSignalInScalarCal();
				//把信号量数据存入对应的信号管道
				offerGpsSaveQueue(vehicle,signal);
				calculateRoadAlarm(vehicle, signal);
				if("08".equals(vehicle.equipmentKind)){
					// 根据当前的GpsSignal对象计算变化量
					DumperSignalWorkCal workCal = new DumperSignalWorkCal(signal, vehicle);
					GpsSignalWork work = workCal.cal();
					if (null != work) {
						CacheManager.instance().getDumperWorkSaveQueue(vehicle.company).offer(work);
					}
				}
				//放入缓存管道，每10分钟进行一次补点 
				CacheManager.instance().getRoadSignalForTelematicsQueue(signal.gpsNo).offer(signal);
				vehicle.lastGps = signal;
			}
			Thread.currentThread().interrupt();
		} catch (Exception e) {
			Logger.err(e);
		}
	}
	
	//把信号量数据存入对应的信号管道
	public void offerGpsSaveQueue(Road_Vehicle vehicle, Road_GpsSignal signal) {		
		if (signal instanceof Road_GpsSignal_Dumper){
			CacheManager.instance().getGpsSaveQueue_Dumper(vehicle.company).offer(signal);
		}else if(signal instanceof Road_GpsSignal_Paver){
			if(((Road_GpsSignal_Paver) signal).paverTemp > 190 && vehicle.lastGps != null){
				((Road_GpsSignal_Paver) signal).paverTemp = vehicle.lastGps.paverTemp;
			}
			signal.paverTemp = ((Road_GpsSignal_Paver) signal).paverTemp;
			CacheManager.instance().getGpsSaveQueue_Paver(vehicle.company).offer(signal);
		}else if(signal instanceof Road_GpsSignal_Roller){
			CacheManager.instance().getGpsSaveQueue_Roller(vehicle.company).offer(signal);
		}
	}
	
	/**
	 * 公路报警
	 */
	private void calculateRoadAlarm(Road_Vehicle vehicle, Road_GpsSignal signal){
		RoadAlarmInfo ai = null;
		for(RoadAlarmRule rule : vehicle.roadAlarmRuleMap.values()){
				try {
					ai = rule.doRoadAlarm(vehicle, signal);
					if (null != ai) {
						CacheManager.instance().getRoadAlarmSaveQueue(vehicle.company).offer(ai);
						//NoticeMessageTool.checkRoadSendMessag(ai.signalId,ai.gpsNo, ai.AlarmType, signal, ai);	
					}
				} catch (Exception e) {
					Logger.err(e);
				}
		}
	}
	
}
